﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.IO;
using Ionic.Zip;
using FRW.Common.Configuration;

namespace FRW.CreateTestDirectory
{
    public partial class MainForm : Form, ILog
    {
        Doc _doc = new Doc();
        Progress _progressDisplay = new Progress();

        Configuration<ApplicationConfiguration> _configuration;

        public MainForm()
        {
            InitializeComponent();

            _configuration = new Configuration<ApplicationConfiguration>();

            if(!_configuration.Load())
            {
                _configuration.LoadDefault();
            }

            _startButton.Enabled = false;

            _sourceDirectory.Text = _configuration.Item.SourceDirectory;
            _destinationDirectory.Text = _configuration.Item.DestinationDirectory;
            _createZipFile.Checked = _configuration.Item.CreateZip;
            FileSize.Text = _configuration.Item.FileSize.ToString();
            _zipFileName.Text = _configuration.Item.ZipFileName;

            _doc.SetStatusInterface(_progressDisplay);
            _doc.SetLogInterface(this);
            _doc.Finished += new EventHandler(_doc_Finished);
        }

        void _doc_Finished(object sender, EventArgs e)
        {
            ResetForm();
        }

        private void ResetForm()
        {
            if (_startButton.InvokeRequired)
            {
                _startButton.Invoke(new Action(() => ResetForm()));
            }
            else
            {
            }
        }

        private void UpdateLog(RichTextBox logText, string logMessage)
        {
            if (logText.InvokeRequired)
            {
                logText.Invoke(new Action( () => _logText.AppendText(logMessage) ));
            }
            else
            {
                _logText.AppendText(logMessage);
            }
        }

        private void _startButton_Click(object sender, EventArgs e)
        {
            _doc.CreateZip = _createZipFile.Checked;
            _doc.Filesize = GetFileSize();
            _doc.Destination = _destinationDirectory.Text;
            _doc.Source = _sourceDirectory.Text;
            _doc.ZipFilename = _zipFileName.Text;

            _doc.Start();
            _progressDisplay.StartPosition = FormStartPosition.CenterParent;
            if (_progressDisplay.ShowDialog() == System.Windows.Forms.DialogResult.Cancel)
            {
                _doc.Cancel();
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        private int GetFileSize()
        {
            int fileSize = 0;

            try
            {
                fileSize = Convert.ToInt32(FileSize.Text);
            }
            catch (FormatException)
            {
                // if we error on value then leave set at 0
            }
            catch (OverflowException)
            {
                fileSize = Int32.MaxValue;
            }

            return fileSize;
        }

        private void SelectSource_Click(object sender, EventArgs e)
        {
            if (_sourceDirectory.Text != "")
            {
                _selectDirectory.SelectedPath = _sourceDirectory.Text;
            }
            _selectDirectory.Description = "Select Source Folder";
            _selectDirectory.ShowNewFolderButton = false;
            _selectDirectory.ShowDialog();
            _sourceDirectory.Text = _selectDirectory.SelectedPath;
        }

        private void SelectDestination_Click(object sender, EventArgs e)
        {
            if (_destinationDirectory.Text != "")
            {
                _selectDirectory.SelectedPath = _destinationDirectory.Text;
            }
            _selectDirectory.Description = "Select Destination Folder";
            _selectDirectory.ShowNewFolderButton = true;

            if (_selectDirectory.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                _destinationDirectory.Text = _selectDirectory.SelectedPath;

                if (_createZipFile.Checked == true && String.IsNullOrWhiteSpace(_zipFileName.Text))
                {
                    _zipFileName.Text = _destinationDirectory.Text + @"\folderStructure.zip";
                }
            }
        }

        private void CreateZip_CheckedChanged(object sender, EventArgs e)
        {
            _zipFileName.Enabled = btnSelectZipFile.Enabled = _createZipFile.Checked;

            if (_createZipFile.Checked == true)
            {
                if (String.IsNullOrWhiteSpace(_zipFileName.Text))
                {
                    if (!String.IsNullOrWhiteSpace(_destinationDirectory.Text))
                    {
                        _zipFileName.Text = _destinationDirectory.Text + @"\folderStructure.zip"; 
                    }
                }
            }
        }

        private void _selectZipFile_Click(object sender, EventArgs e)
        {
            if (_zipFileName.Text != "")
            {
                _selectFile.FileName = _zipFileName.Text;
            }
            else
            {
                //SelectFile.FileName = DestinationDirectory.Text + @"\destination.zip";
            }
            _selectFile.AddExtension = true;
            _selectFile.DefaultExt = ".zip";
            _selectFile.CheckFileExists = false;
            if (_selectFile.ShowDialog() == DialogResult.OK)
            {
                _zipFileName.Text = _selectFile.FileName;
            }

        }

        private void _sourceDirectory_TextChanged(object sender, EventArgs e)
        {
            CheckOptions();
            ToolTip tooltip = new ToolTip();

            if (!Directory.Exists(_sourceDirectory.Text))
            {
                _sourceDirectory.BackColor = Color.Red;
                tooltip.ToolTipTitle = "Error";
                tooltip.IsBalloon = true;
                tooltip.SetToolTip(_sourceDirectory, "Directory does not exist");
                statusText.Text = "Source directory does not exist";
            }
            else
            {
                _sourceDirectory.BackColor = SystemColors.Window;
                statusText.Text = "";
            }
        }

        private void _destinationDirectory_TextChanged(object sender, EventArgs e)
        {
            try
            {
                DirectoryInfo directoryInfo = new DirectoryInfo(_destinationDirectory.Text);

                if (directoryInfo.Exists && (directoryInfo.EnumerateFiles().Count() > 0 || directoryInfo.EnumerateDirectories().Count() > 0))
                {
                    _destinationDirectory.BackColor = Color.Red;
                    statusText.Text = "Destination folder not empty";
                }
                else
                {
                    _destinationDirectory.BackColor = Color.White;
                    if(statusText.Text.Equals("Destination folder not empty"))
                    {
                        statusText.Text = "";
                    }
                }

                CheckOptions();
            }
            catch
            {
                CheckOptions();
            }
        }

        private void CheckOptions()
        {
            if (Directory.Exists(_sourceDirectory.Text) && !String.IsNullOrWhiteSpace(_destinationDirectory.Text))
            {
                _startButton.Enabled = true;
            }
            else
            {
                _startButton.Enabled = false;
            }
        }

        private void FileSize_KeyDown(object sender, KeyEventArgs e)
        {
            switch (e.KeyData)
            {
                // we allow cursor keys, delete and backspace so that we can edit control
                case Keys.Left:
                case Keys.Right:
                case Keys.Delete:
                case Keys.Back:
                    break;

                // Accept all the number keys
                case Keys.D0:
                case Keys.D1:
                case Keys.D2:
                case Keys.D3:
                case Keys.D4:
                case Keys.D5:
                case Keys.D6:
                case Keys.D7:
                case Keys.D8:
                case Keys.D9:
                    break;

                // Also accept number pad keys
                case Keys.NumPad0:
                case Keys.NumPad1:
                case Keys.NumPad2:
                case Keys.NumPad3:
                case Keys.NumPad4:
                case Keys.NumPad5:
                case Keys.NumPad6:
                case Keys.NumPad7:
                case Keys.NumPad8:
                case Keys.NumPad9:
                    break;

                // Anything else then we ignore
                default:
                    e.SuppressKeyPress = true;
                    break;
            }
        }

        public void Log(string text)
        {
            UpdateLog(_logText, text);
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            int filesize = 0;

            _configuration.Item.SourceDirectory = _sourceDirectory.Text;
            _configuration.Item.DestinationDirectory = _destinationDirectory.Text;
            _configuration.Item.CreateZip = _createZipFile.Checked;
            _configuration.Item.ZipFileName = _zipFileName.Text;
            
            try
            {
                filesize = Convert.ToInt32(FileSize.Text);
            }
            catch
            {
            }
            _configuration.Item.FileSize = filesize;

            _configuration.Save();
        }
    }
}
